package com.wink_172.activity

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import com.wink_172.commons.R
import com.wink_172.commons.databinding.ActivityFirstBinding
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.CommonUtils
import com.wink_172.library.utils.DisplayUtil
import com.wink_172.library.utils.ImageUtil
import org.xutils.common.Callback
import org.xutils.common.Callback.CancelledException
import org.xutils.x
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import android.animation.ObjectAnimator
import android.database.Cursor
import android.os.Message
import android.provider.ContactsContract
import com.wink_172.library.utils.DateUtil
import com.wink_172.library.utils.SoundPlayerUtil
import java.lang.Exception


class TestActivity : SmartActivity() {
    lateinit var binding: ActivityFirstBinding

    companion object {
        open fun startActivity(context: Context) {

            //apply用法 kotlin-P132
            val intent = Intent(context, TestActivity::class.java).apply {
                putExtra(Constants.PARAM_DATA1, "hello01");
                putExtra(Constants.PARAM_DATA2, "hello02");
                putExtra(Constants.PARAM_DATA3, "hello03");
            }

            context.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_first)




        initView()
        Log.e(TAG, "onCreate: ====>DecimalFormat:" + DecimalFormat("0").format(366.toLong()))
        Log.e(TAG, "onCreate: ====>DecimalFormat:" + DecimalFormat("0").format("06".toLong()))
        Log.e(TAG, "onCreate: ====>DecimalFormat:" + DecimalFormat("0").format("36".toLong()))

        val sound1= SoundPlayerUtil(this);
        sound1.play(R.raw.cherry_hand_110000); //播放321声音



        val str1=DateUtil.getChatTimeStr2(1650443192);
        Log.e(TAG, "str: ====>>str1:"+str1 )

//        Log.e(TAG, "randFloatBetween: ====>>"+DateUtil.longToString(1636005969000,  DateUtil.FORMAT_MONTH_DAY_TIME) )
        x.image().bind(binding!!.img!!, CommonUtils.randomImageUrl,
            object :
                Callback.CommonCallback<Drawable> {
                override fun onSuccess(result: Drawable?) {
                    Log.e(TAG, "onSuccess: ====>>")
//
                    val bit = ImageUtil.drawableToBitamp(result) as Bitmap


                    //先获取对图片形状处理的帮助类
                    //先获取对图片形状处理的帮助类
//                    binding!!.img!!.setImageBitmap(bb)
                }

                override fun onError(ex: Throwable?, isOnCallback: Boolean) {
                    Log.e(TAG, "onError: ====>>")
                }

                override fun onCancelled(cex: CancelledException?) {
                    Log.e(TAG, "onCancelled: ====>>")
                }

                override fun onFinished() {
//                    Log.e(TAG, "onFinished: ====>>")
                }


            }

        )



        for (i in 0..0) {
            addSingleAvater()
        }
        val all_count = binding!!.imageContainer.childCount

        val msg = Message()
        msg.what = 1000
        msg.arg1 = all_count - 1

        getHandle().removeMessages(1000)
        getHandle().sendMessageDelayed(msg, 3000)


        readContacts()
    }


    fun removeSingleAvater() {
        val all_count = binding!!.imageContainer.childCount
//        val image_view = binding!!.imageContainer.get(all_count - 1) as ImageView

        binding!!.imageContainer.removeViewAt(all_count - 1)

    }

    /**
     * 获取通讯录  需要通讯录权限
     * android.permission.READ_CONTACTS
     * */
     fun readContacts() {
        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, null
            )
            while (cursor!!.moveToNext()) {
                val i_name =
                    cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                val displayName = cursor.getString(i_name)
                val i_number = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                val number = cursor.getString(i_number)
                Log.e(TAG, "readContacts: ====>>:$displayName    :$number")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
    }


    fun addSingleAvater() {
        val image = LayoutInflater.from(binding!!.root.context)
            .inflate(R.layout.item_praise, binding!!.imageContainer, false) as ImageView
        image.alpha = 0.8f

        val lp: ViewGroup.MarginLayoutParams = ViewGroup.MarginLayoutParams(
            DisplayUtil.dp2px(x.app(), 50f),
            DisplayUtil.dp2px(x.app(), 50f)
        )
//            image.layoutParams=lp
        x.image().bind(image, CommonUtils.randomImageUrl)
        binding!!.imageContainer.addView(image, 0)
    }

    var view1: ImageView? = null
    var view2: ImageView? = null

    override fun handlerCallBack(msg: Message?) {
        super.handlerCallBack(msg)
        val time2=800L
        when (msg!!.what) {
            1000 -> {//平移放大
                val pos = msg.arg1
                val image_view = binding!!.imageContainer.getChildAt(pos) as ImageView
                view1 = image_view

                val time=1200L

                val animator = ObjectAnimator.ofFloat(view1!!, "alpha", 0.8f, 1f)
                animator.duration = time
                animator.start()


                val animator2 = ObjectAnimator.ofFloat(view1, "scaleY", 1f, 1.2f)
                animator2.duration = time2
                animator2.start()

                val animator4 = ObjectAnimator.ofFloat(view1, "scaleX", 1f, 1.2f)
                animator4.duration = time2
                animator4.start()

                val curTranslationX: Float = view1!!.getTranslationX()
                val animator3 = ObjectAnimator.ofFloat(
                    view1,
                    "translationX",
                    curTranslationX,
                    -80f,
                    -80f
                )


                animator3.duration = time
                animator3.start()

                view2 = view1


                addSingleAvater()

                if (first == false) {
                    x.task().postDelayed(Runnable {
                        removeSingleAvater()
                    },time)

                }
                first = false
                getHandle().removeMessages(1001)
                getHandle().sendEmptyMessageDelayed(1001, 2000)
            }


            1001 -> {//alp减小动画
                val animator = ObjectAnimator.ofFloat(view2!!, "alpha", 1.0f, 0f)
                animator.duration = time2
                animator.start()


                val all_count = binding!!.imageContainer.childCount

                val msg = Message()
                msg.what = 1000
                msg.arg1 = all_count - 2
                getHandle().removeMessages(1000)
                getHandle().sendEmptyMessageDelayed(1000, 0)
            }

        }
    }

    private val TAG = "TestActivity"

    var first = true

    /**
     * 获取最近一周的时间 MM-dd
     */
    private fun getCurrentWeekDay(): List<String>? {
        val data: MutableList<String> = ArrayList()
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_MONTH, -7)
        val sdf = SimpleDateFormat("MM-dd")
        for (i in 0..6) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            data.add(sdf.format(calendar.time))
        }
        return data
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            Constants.ACTIVITY_REQUEST_CODE3001 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
//                    denied
                }


            }
        }
    }

    fun initView() {

    }


}